from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from sqlalchemy import create_engine, Column, Integer, String, Text
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from pydantic import BaseModel
from datetime import datetime
import os
import zipfile
import tempfile

# 数据库配置
DATABASE_URL = "sqlite:///./translations.db"
engine = create_engine(DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()

# 数据模型
class Translation(Base):
    __tablename__ = "translations"
    
    id = Column(Integer, primary_key=True, index=True)
    key = Column(String, unique=True, index=True)
    english = Column(Text)
    chinese = Column(Text)

# 创建数据库表
Base.metadata.create_all(bind=engine)

# Pydantic模型
class TranslationCreate(BaseModel):
    key: str
    english: str
    chinese: str

class TranslationUpdate(BaseModel):
    key: str
    english: str
    chinese: str

class BuildConfig(BaseModel):
    version: str
    includes: list[str]

# FastAPI应用
app = FastAPI(title="PKHeX-Plugins 本地化工具", version="1.0.0")

# CORS配置
app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://localhost:5173"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 静态文件服务
if not os.path.exists("downloads"):
    os.makedirs("downloads")
app.mount("/downloads", StaticFiles(directory="downloads"), name="downloads")

# 获取数据库会话
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

# API路由
@app.get("/api/translations")
def get_translations(db: SessionLocal = next(get_db())):
    return db.query(Translation).all()

@app.post("/api/translations")
def create_translation(translation: TranslationCreate, db: SessionLocal = next(get_db())):
    db_translation = Translation(**translation.dict())
    db.add(db_translation)
    db.commit()
    db.refresh(db_translation)
    return db_translation

@app.put("/api/translations/{translation_id}")
def update_translation(translation_id: int, translation: TranslationUpdate, db: SessionLocal = next(get_db())):
    db_translation = db.query(Translation).filter(Translation.id == translation_id).first()
    if not db_translation:
        raise HTTPException(status_code=404, detail="Translation not found")
    
    for key, value in translation.dict().items():
        setattr(db_translation, key, value)
    
    db.commit()
    db.refresh(db_translation)
    return db_translation

@app.delete("/api/translations/{translation_id}")
def delete_translation(translation_id: int, db: SessionLocal = next(get_db())):
    db_translation = db.query(Translation).filter(Translation.id == translation_id).first()
    if not db_translation:
        raise HTTPException(status_code=404, detail="Translation not found")
    
    db.delete(db_translation)
    db.commit()
    return {"message": "Translation deleted"}

@app.post("/api/build")
def build_package(config: BuildConfig, db: SessionLocal = next(get_db())):
    # 创建临时目录
    with tempfile.TemporaryDirectory() as temp_dir:
        # 创建语言包目录结构
        lang_dir = os.path.join(temp_dir, "zh-CN")
        os.makedirs(lang_dir)
        
        # 生成翻译文件
        translations = db.query(Translation).all()
        with open(os.path.join(lang_dir, "translations.json"), "w", encoding="utf-8") as f:
            import json
            json.dump({t.key: {"english": t.english, "chinese": t.chinese} for t in translations}, f, ensure_ascii=False, indent=2)
        
        # 创建README文件
        with open(os.path.join(temp_dir, "README.txt"), "w", encoding="utf-8") as f:
            f.write("PKHeX-Plugins 简体中文语言包\n")
            f.write("============================\n\n")
            f.write("安装说明：\n")
            f.write("1. 解压本压缩包\n")
            f.write("2. 将 zh-CN 文件夹复制到 PKHeX-Plugins 目录\n")
            f.write("3. 重启 PKHeX 即可生效\n")
        
        # 创建ZIP文件
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        filename = f"PKHeX-Plugins-zh-CN-{config.version}-{timestamp}.zip"
        zip_path = os.path.join("downloads", filename)
        
        with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
            for root, dirs, files in os.walk(temp_dir):
                for file in files:
                    file_path = os.path.join(root, file)
                    arcname = os.path.relpath(file_path, temp_dir)
                    zipf.write(file_path, arcname)
        
        # 计算文件大小
        file_size = os.path.getsize(zip_path)
        size_mb = round(file_size / (1024 * 1024), 2)
        
        return {
            "filename": filename,
            "size": f"{size_mb} MB",
            "created_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
            "download_url": f"/downloads/{filename}"
        }

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)
